package apicmd

import (
	"emsctrl/ctrlMode"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"strings"
	"time"
)

var G_mng *ctrlMode.Ctrl_Mode_Mng

func cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("origin")
		var headerkeys []string
		for k, _ := range c.Request.Header {
			headerkeys = append(headerkeys, k)
		}
		headerstr := strings.Join(headerkeys, ",")
		if headerstr != "" {
			headerstr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerstr)
		} else {
			headerstr = "access-control-allow-origin, access-control-allow-headers"
		}
		if origin != "" {
			origin = c.Request.Header.Get("Origin")
			c.Header("Access-Control-Allow-Origin", origin)
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization,Access-Control-Allow-Origin")
			c.Header("Access-Control-Max-Age", "172800")
			c.Header("Acess-Control-Allow-Credentials", "false")
			c.Set("content-type", "application/json")
		}
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "Options Request!")
		}
		c.Next()
	}
}

func ApiInit(mng *ctrlMode.Ctrl_Mode_Mng) {
	engine := gin.Default()
	engine.Use(cors())
	group := engine.Group("/v1")
	{

		group.POST("/policy/set", api_policy_set)
		group.GET("/policy/get", api_policy_get)

	}
	go engine.Run("127.0.0.1:9900")
	G_mng = mng

	//go DbRead()
}

func api_policy_get(ctx *gin.Context) {
	fmt.Println(ctx.Request.Body)
}

func api_policy_set(ctx *gin.Context) {
	all, err := io.ReadAll(ctx.Request.Body)
	fmt.Println(string(all), err)
	G_mng.Api_Policy_Config(all)
	_, exists := ctx.Get("Access-Control-Allow-Origin")
	if exists {
		ctx.Header("Access-Control-Allow-Origin", "*")
	}
	ctx.JSON(200, gin.H{"return": "ok"})
}

func DbRead() {
	for {
		time.Sleep(time.Second * 1)
		GetGridMeter_Power()
	}
}
